"""
mqtt任务模块
日期: 2024/12/21
"""
from settings import ProductionConfig as current_config

# MQTT状态
MQTT_STATE = {
    0: 'MQTT 未初始化',
	1: '已设置 AT+MQTTUSERCFG',
	2: '已设置 AT+MQTTCONNCFG',
	3: '连接已断开',
	4: '已建立连接',
	5: '已连接，但未订阅 topic',
	6: '已连接，已订阅过 topic',
    }

MQTT_SCHEME = {
    1: 'MQTT over TCP',
	2: 'MQTT over TLS（不校验证书）',
	3: 'MQTT over TLS（校验 server 证书）',
	4: 'MQTT over TLS（提供 client 证书）',
	5: 'MQTT over TLS（校验 server 证书并且提供 client 证书）',
	6: 'MQTT over WebSocket（基于 TCP）',
	7: 'MQTT over WebSocket Secure（基于 TLS，不校验证书）',
	8: 'MQTT over WebSocket Secure（基于 TLS，校验 server 证书）',
	9: 'MQTT over WebSocket Secure（基于 TLS，提供 client 证书）',
	10: 'MQTT over WebSocket Secure}',
    }


class TaskMqtt():
    def __init__(self, at):
        self.at = at

    def init(self):
        brokerinfo = self.at.mqtt_brokerinfo  # 读取设置的broker服务器信息
        if brokerinfo[0]:
            if brokerinfo[2] in [0, 3]:  # 未初始化或连接断开,重新设置
                self.at.mqtt_set(current_config.MQTT_HOST_BEMFA, current_config.MQTT_PORT_BEMFA, current_config.MQTT_ID_BEMFA)  # 设置mqtt
            elif brokerinfo[2] in [4, 5]:  # 未订阅
                self.at.mqtt_subscribe(topic=current_config.SUBJECT_SUBSCRIBE)  # 订阅指定主题
        
        else:
            print(f'获取brokerinfo失败:{brokerinfo[1]}')
        
    
    # 发布消息,注意消息中不能有逗号,否则返回错误
    def publish(self, msg):
        returned = self.at.mqtt_publish(current_config.SUBJECT_PUBLISH, msg)
        return returned


    # 等待接收订阅消息, 目前暂返回消息本体
    def wait_for_subscribed(self):
        return_status, subject, message, delay = self.at.mqtt_wait_for_subscribed()
        return message
    